﻿//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace EffiProzDB.Lib
{
    public class Properties : Dictionary<string,string>
    {
        public Properties()
        {
        }

        public  Properties(Properties Defaults)
        {

        }

        public string GetProperty(string key)
        {
            if (base.ContainsKey(key))
                return base[key];
            else
                return null;
        }

        public string GetProperty(String key, String defaultValue)
        {
            if (base.ContainsKey(key))
                return base[key];
            else
                return defaultValue;
        }

        public KeyCollection PropertyNames()
        {
            return base.Keys;
        }

        public void Load(string file_path)
        {
            foreach (var row in File.ReadAllLines(file_path))
                if(!row.Trim().StartsWith("#"))
                {
                    if (!row.Trim().StartsWith("#"))
                    {
                        string[] pair = row.Split('=');
                        base[pair[0]] = pair[1];
                    }
                }
        }

        public void Load(Stream ips)
        {
            StreamReader sr = new StreamReader(ips);
            string[] lines = sr.ReadToEnd().Split(Environment.NewLine.ToCharArray());
            foreach (var row in lines)
            {
                if (!row.Trim().StartsWith("#"))
                {
                    string[] pair = row.Split('=');
                    base[pair[0]] = pair[1];
                }
            }
        }

        public void Store(Stream ips, string comments)
        {
            StreamWriter sr = new StreamWriter(ips);
            sr.WriteLine("# " + comments);
            foreach (var it in this)
            {
                sr.WriteLine(it.Key+"=" + it.Value);
            }
            sr.Flush();
        }


        public void SetProperty(string key, string value)
        {
            base[key] = value;
        }

        public void List(StreamWriter sw)
        {
            foreach (var key in base.Keys)
                sw.Write(key + "=" + base[key]);

        }

        public void List(Stream os)
        {
            StreamWriter sw = new StreamWriter(os);
            foreach (var key in base.Keys)
                sw.Write(key + "=" + base[key]);

        }

    }
}
